package com.ctsi.question.controller;


import com.ctsi.commons.util.UtilDateTime;
import com.ctsi.commons.util.UtilMisc;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.id.UUIDGenerator;
import com.ctsi.commons.util.request.UtilHttp;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.common.response.UnifiedResponse;
import com.ctsi.framework.mybatis.support.VoTemplate;
import com.ctsi.framework.organise.security.UserInfo;
import com.ctsi.framework.security.util.SecurityUtil;
import com.ctsi.question.entity.DayReportEntity;
import com.ctsi.question.entity.DayReportLeaderEntity;
import com.ctsi.question.entity.DayreportQuery;
import com.ctsi.question.entity.ReportQuery;
import com.ctsi.question.service.DayReportEntityService;
import com.ctsi.question.service.DayReportLeaderEntityService;
import com.ctsi.question.vo.DayReportLeaderVO;
import com.ctsi.question.vo.ReportVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.ctsi.commons.util.UtilDateTime.defaultDatePattern;

@RestController
public class DayReportController {

    private static final Logger logger = LoggerFactory.getLogger(DayReportController.class);
    @Autowired
    private DayReportEntityService dayReportEntityService;
    @Autowired
    private VoTemplate voTemplate;
    @Autowired
    private DayReportLeaderEntityService dayReportLeaderEntityService;

    /**
     *添加日报
     *
     * */
    @PostMapping(value = "/report/addDayReport", consumes = "application/json", produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Integer> addReport(@RequestBody DayReportEntity reportEntity) {
        UserInfo user = SecurityUtil.getUser();
        String userId = user.getUserId();
        reportEntity.setId(UUIDGenerator.getId());
        reportEntity.setUserId(userId);
        reportEntity.setPostMan(user.getFullName());
        reportEntity.setDepartMent(user.getDepartName());
        reportEntity.setCreateTime(System.currentTimeMillis());
        reportEntity.setIs_delete(0);
        reportEntity.setIs_read(0);
        int i = dayReportEntityService.insertDayReportEntity(reportEntity);
        return UnifiedResponse.ok(i);
    }
    /**
     * 日报详情
     *
     */
    @PostMapping(value = "/report/selectDayReportById",produces = "application/json;charset=UTF-8" )
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<ReportVO> selectReportById(@RequestParam("id") String id){
        if (UtilValidate.isEmpty(id)){
            return UnifiedResponse.ok(null);
        }
        DayReportEntity reportEntity = dayReportEntityService.findDayReportEntityById(id);
        ReportVO reportVO=voTemplate.defaultExcute(new ReportVO(),reportEntity);
        reportVO.setCreateDateStr(UtilDateTime.longToString(reportEntity.getCreateTime()));
        return UnifiedResponse.ok(reportVO);
    }
    /**
     * 日报详情  APP专用（是否已阅）
     *
     */
    @PostMapping(value = "/report/selectShowDayReport",produces = "application/json;charset=UTF-8" )
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<ReportVO> selectShowDayReport(@RequestParam("id") String id){
        if (UtilValidate.isEmpty(id)){
            return UnifiedResponse.ok(null);
        }
        DayReportEntity reportEntity = dayReportEntityService.findDayReportEntityById(id);
        ReportVO reportVO=voTemplate.defaultExcute(new ReportVO(),reportEntity);
        reportVO.setCreateDateStr(UtilDateTime.longToString(reportEntity.getCreateTime()));
        DayReportEntity dayReportEntity=new DayReportEntity();
        dayReportEntity.setId(id);
        dayReportEntity.setIs_read(1);
        dayReportEntityService.updateDayReportEntityByPKSelective(dayReportEntity);
        return UnifiedResponse.ok(reportVO);
    }
    /**
     * 更新日报
     */
    @PostMapping(value = "/report/editDayReport", consumes = "application/json", produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Integer> editReport(@RequestBody DayReportEntity reportEntity) {
        int i = dayReportEntityService.updateDayReportEntityByPKSelective(reportEntity);
        return UnifiedResponse.ok(i);
    }
    /**
     * 日报列表(当前登陆用户)
     *
     */
    @PostMapping(value = "/report/queryDayReportListById",consumes = "application/json",produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Page<ReportVO>> queryReportListById(@RequestBody ReportQuery ppp){
        ppp.setUserId(SecurityUtil.getUser().getUserId());
        Page<DayReportEntity> result = dayReportEntityService.findByMulitCondition(UtilHttp.filterBlank(UtilMisc.toMap(ppp)),ppp.getStart(),ppp.getPageSize());
        List<ReportVO> reportVOS=result.getResult().stream().map(lib ->{
            ReportVO reportVO=voTemplate.defaultExcute(new ReportVO(),lib);
            reportVO.setCreateDateStr(UtilDateTime.longToString(lib.getCreateTime()));
            return reportVO;
        }).collect(Collectors.toList());
        return UnifiedResponse.ok(new Page<>(ppp.getStart(),result.getTotalCount(),result.getPageSize(),reportVOS));
    }

    /**
     * 删除日报
     */
    @PostMapping(value = "/question/deleteDayReportById", produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<String> deleteQuestionById(@RequestParam("ids") String ids) {
        if (UtilValidate.isNotEmpty(ids)) {
            List<String> arr = new ArrayList<>();
            if (!ids.contains(",")) {
                arr.add(ids);
            } else {
                arr = Arrays.asList(ids.split(","));
            }
            int result = arr.stream().parallel().filter(id -> UtilValidate.isNotEmpty(id)).mapToInt(id -> {
                try {
                    DayReportEntity question = new DayReportEntity();
                    question.setId(id);
                    question.setIs_delete(1);
                    return this.dayReportEntityService.updateDayReportEntityByPKSelective(question);
                } catch (Exception e) {
                    logger.error("{}", e);
                    return 0;
                }
            }).sum();
            if (arr.size() > 1) {
                return UnifiedResponse.ok("选中" + arr.size() + "条数据，成功删除" + result + "条数据！");
            } else {
                return UnifiedResponse.ok("删除成功!");
            }
        }
        return UnifiedResponse.ok("删除成功!");
    }

    /**
     * 录入领导批示
     */
    @PostMapping(value = "/report/addReportLeader", consumes = "application/json", produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Integer> addReportLeader(@RequestBody DayReportLeaderEntity reportEntity) {
        UserInfo user = SecurityUtil.getUser();
        String userId = user.getUserId();
        reportEntity.setId(UUIDGenerator.getId());
        reportEntity.setMasterId(userId);
        reportEntity.setMasterName(user.getFullName());
        reportEntity.setSayTime(System.currentTimeMillis());
        int i = dayReportLeaderEntityService.insertDayReportLeaderEntity(reportEntity);
        return UnifiedResponse.ok(i);
    }

    /**
     * 领导批示列表
     */
    @PostMapping(value = "/report/queryReportLeaderListById",consumes = "application/json",produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Page<DayReportLeaderVO>> queryReportLeaderListById(@RequestBody DayreportQuery ppp){
        Page<DayReportLeaderEntity> result = dayReportLeaderEntityService.findByMulitCondition(UtilHttp.filterBlank(UtilMisc.toMap(ppp)),ppp.getStart(),ppp.getPageSize());
        List<DayReportLeaderVO> reportVOS=result.getResult().stream().map(lib ->{
            DayReportLeaderVO reportVO=voTemplate.defaultExcute(new DayReportLeaderVO(),lib);
            reportVO.setSayTimeStr(UtilDateTime.longToString(lib.getSayTime()));
            return reportVO;
        }).collect(Collectors.toList());
        return UnifiedResponse.ok(new Page<>(ppp.getStart(),result.getTotalCount(),result.getPageSize(),reportVOS));
    }

    /**
     * APP-领导默认查看当天日报列表
     */
    @PostMapping(value = "/report/queryNowReportListById",consumes = "application/json",produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Page<ReportVO>> queryNowReportListById(@RequestBody ReportQuery ppp){
        if(UtilValidate.isNotEmpty(ppp.getCreateTime())){
            ppp.setCreateTime(ppp.getCreateTime());
        }else {
            ppp.setCreateTime(UtilDateTime.longToString(System.currentTimeMillis(),defaultDatePattern));
        }
        if (UtilValidate.isNotEmpty(ppp.getPostMan())){
            ppp.setPostMan("%"+ppp.getPostMan()+"%");
        }
//        Map<String, Object> stringObjectMap = dayReportEntityService.selectID(SecurityUtil.getUser().getUserId());
//        ppp.setPersonId((String) stringObjectMap.get("id"));
        ppp.setPersonId(SecurityUtil.getUser().getUserId());
        Page<DayReportEntity> result = dayReportEntityService.selectMulitConditionLeader(UtilHttp.filterBlank(UtilMisc.toMap(ppp)),ppp.getStart(),ppp.getPageSize());
        List<ReportVO> reportVOS=result.getResult().stream().map(lib ->{
            ReportVO reportVO=voTemplate.defaultExcute(new ReportVO(),lib);
            if (lib.getCreateTime()!=null){
                reportVO.setCreateDateStr(UtilDateTime.longToString(lib.getCreateTime()));
            }
            return reportVO;
        }).collect(Collectors.toList());
        return UnifiedResponse.ok(new Page<>(ppp.getStart(),result.getTotalCount(),result.getPageSize(),reportVOS));
    }

    /**
     * 批示详情
     */
    @PostMapping(value = "/report/selectLeaderSay",produces = "application/json;charset=UTF-8" )
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<DayReportLeaderVO> selectLeaderSay(@RequestParam("id") String id){
        if (UtilValidate.isEmpty(id)){
            return UnifiedResponse.ok(null);
        }
        DayReportLeaderEntity dayReportLeaderEntity = dayReportLeaderEntityService.findDayReportLeaderEntityById(id);
        DayReportLeaderVO dayReportLeaderVO=voTemplate.defaultExcute(new DayReportLeaderVO(),dayReportLeaderEntity);
        dayReportLeaderVO.setSayTimeStr(UtilDateTime.longToString(dayReportLeaderEntity.getSayTime()));
        return UnifiedResponse.ok(dayReportLeaderVO);
    }


}
